import { getToken, setToken, removeToken } from '@/utils/auth'
import { login, getUserProfile } from '@/api'
import { resetRouter } from '@/router'
const state = {
  token: getToken(), //    token持久化 => 放到缓存中
  userInfo: {}
}
// 修改状态
const mutations = {
  // 设置token
  setToken (state, data) {
    state.token = data.token
    setToken(data.token)
  },
  // 删除缓存
  removeToken (state) {
    state.token = null
    removeToken()
  },
  // 设置用户资料信息
  setUserInfo (state, data) {
    state.userInfo = data
  }
}
// 执行异步
const actions = {
  // 登录
  async login ({ commit }, data) {
    const result = await login(data)
    commit('setToken', result)
  },
  // 退出
  async logout ({ commit }) {
    commit('removeToken')
    commit('setUserInfo', {})
    resetRouter() // 重置路由
  },
  // 拉取用户信息
  async getUserInfo ({ commit, dispatch }) {
    const res = await getUserProfile()
    commit('setUserInfo', res.userInfo)
    // 将数据存储到permission模块
    // 调用permission处理出来路由  一定要await，否则路由还没有成功
    await dispatch('permission/generateRoutes', res.menuList, { root: true })
    // 处理按钮权限
    await commit('permission/setBtnList', res.btnList, { root: true })
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
